package com.ztn.sdk.iot.api.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.IOException;

public class JsonTool {

    private final static Logger log = LoggerFactory.getLogger(HttpTool.class);

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }


    public static String toJson(Object src) {
        if (null == src) {
            return "";
        }
        try {
            return objectMapper.writeValueAsString(src);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
            return null;
        }
    }

//    public static String toJson(Object src, boolean withNoNull) {
//        if(!StringUtils.hasText(src)){
//            return "";
//        }
//        if (withNoNull) {
//            try {
//                return objectWithNoNullMapper.writeValueAsString(src);
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//                return null;
//            }
//        }
//        return toJson(src);
//
//    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        if (null == json) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            log.error(json);
            log.error(e.getMessage());
            return null;
        }

    }

    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        if (null == json) {
            return null;
        }
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (IOException e) {
            log.error(json);
            log.error(e.getMessage());
            return null;
        }
    }
}
